package org.yinweichen.llm_dataset_backend.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yinweichen.llm_dataset_backend.entity.*;
import org.yinweichen.llm_dataset_backend.repository.*;
import org.yinweichen.llm_dataset_backend.service.VersionService;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class VersionServiceImpl implements VersionService {

    private final VersionRepository versionRepository;
    private final OriginalQuestionRepository originalQuestionRepository;
    private final OriginalAnswerRepository originalAnswerRepository;
    private final StandardQuestionRepository standardQuestionRepository;
    private final StandardAnswerRepository standardAnswerRepository;
    private final PointsRepository pointsRepository;
    private final QuestionTagRepository questionTagRepository;

    public VersionServiceImpl(VersionRepository versionRepository,
                           OriginalQuestionRepository originalQuestionRepository,
                           OriginalAnswerRepository originalAnswerRepository,
                           StandardQuestionRepository standardQuestionRepository,
                           StandardAnswerRepository standardAnswerRepository,
                           PointsRepository pointsRepository,
                           QuestionTagRepository questionTagRepository) {
        this.versionRepository = versionRepository;
        this.originalQuestionRepository = originalQuestionRepository;
        this.originalAnswerRepository = originalAnswerRepository;
        this.standardQuestionRepository = standardQuestionRepository;
        this.standardAnswerRepository = standardAnswerRepository;
        this.pointsRepository = pointsRepository;
        this.questionTagRepository = questionTagRepository;
    }

    @Override
    @Transactional
    public Version createVersion(String baseVer, String newVer, String description) {
        // 验证新版本号是否已存在
        if (versionRepository.existsById(newVer)) {
            throw new IllegalArgumentException("Version " + newVer + " already exists");
        }

        // 创建新版本对象
        Version newVersion = Version.builder()
                .ver_code(newVer)
                .description(description)
                .time(new Date())
                .published(false)
                .build();

        // 如果有基础版本，复制数据
        if (baseVer != null&&!baseVer.isEmpty()) {
            Optional<Version> baseVersionOpt = versionRepository.findById(baseVer);
            if (baseVersionOpt.isEmpty()) {
                throw new IllegalArgumentException("Base version " + baseVer + " not found");
            }

            Version baseVersion = baseVersionOpt.get();
            if (!baseVersion.getPublished()) {
                throw new IllegalArgumentException("Base version " + baseVer + " is not published");
            }
            // 复制基础版本的数据
            // 1. 复制原始问题
            List<OriginalQuestion> originalQuestions = originalQuestionRepository.findAllByVersion(baseVer);
            for (OriginalQuestion originalQuestion : originalQuestions) {
                OriginalQuestion newQuestion = OriginalQuestion.builder()
                        .id(originalQuestion.getId())
                        .version(newVer)
                        .title(originalQuestion.getTitle())
                        .content(originalQuestion.getContent())
                        .source(originalQuestion.getSource())
                        .active(true)
                        .build();
                originalQuestionRepository.save(newQuestion);

                // 2. 复制关联的原始回答
                List<OriginalAnswer> originalAnswers = originalAnswerRepository.findByOriginalQuestionIdAndVersion(
                        originalQuestion.getId(), baseVer);
                for (OriginalAnswer originalAnswer : originalAnswers) {
                    OriginalAnswer newAnswer = OriginalAnswer.builder()
                            .id(originalAnswer.getId())
                            .version(newVer)
                            .answer(originalAnswer.getAnswer())
                            .originalQuestion(newQuestion)
                            .build();
                    originalAnswerRepository.save(newAnswer);
                }

                // 3. 复制关联的标准问题
                List<StandardQuestion> standardQuestions = standardQuestionRepository.findByOriginalQuestionIdAndOriginalQuestionVersion(
                        originalQuestion.getId(), baseVer);
                for (StandardQuestion standardQuestion : standardQuestions) {
                    StandardQuestion newStandardQuestion = StandardQuestion.builder()
                            .id(standardQuestion.getId())
                            .version(newVer)
                            .question(standardQuestion.getQuestion())
                            .originalQuestion(newQuestion)
                            .category(standardQuestion.getCategory())  // 复制Category字段
                            .active(true)
                            .build();
                    standardQuestionRepository.save(newStandardQuestion);

                    // 复制QuestionTag
                    List<String> questionTags = questionTagRepository.findTagsByQuestionIdAndVersion(
                            standardQuestion.getId(), baseVer);
                    for (String questionTag : questionTags) {
                        QuestionTag newQuestionTag = QuestionTag.builder()
                                .id(standardQuestion.getId())
                                .question(newStandardQuestion)
                                .tag(questionTag)
                                .version(newVer)
                                .build();
                        questionTagRepository.save(newQuestionTag);
                    }

                    // 4. 复制关联的标准回答
                    StandardAnswer standardAnswer = standardAnswerRepository.findById(
                            new StandardAnswerId(standardQuestion.getId(), baseVer))
                            .orElse(null);
                    if (standardAnswer != null) {
                        StandardAnswer newStandardAnswer = StandardAnswer.builder()
                                .questionId(standardAnswer.getQuestionId())
                                .version(newVer)
                                .answer(standardAnswer.getAnswer())
                                .standardQuestion(newStandardQuestion)
                                .build();
                        standardAnswerRepository.save(newStandardAnswer);

                        // 5. 复制关联的Points
                        List<Points> pointsList = pointsRepository.findByAnswerIdAndActiveTrue(
                                standardAnswer.getQuestionId(), baseVer);
                        for (Points points : pointsList) {
                            Points newPoints = Points.builder()
                                    .keyword(points.getKeyword())
                                    .value(points.getValue())
                                    .answer(newStandardAnswer)
                                    .active(true)
                                    .build();
                            pointsRepository.save(newPoints);
                        }
                    }
                }
            }
        }

        // 保存并返回新版本
        return versionRepository.save(newVersion);
    }

    @Override
    @Transactional
    public Version publishVersion(String versionId) {
        // 验证版本存在且未发布
        if (!versionRepository.existsById(versionId)) {
            throw new IllegalArgumentException("Version " + versionId + " not found");
        }

        int updated = versionRepository.publishVersion(versionId, new Date());
        if (updated == 0) {
            throw new IllegalArgumentException("Version " + versionId + " is already published or not found");
        }

        // 删除该版本下不活跃的OriginalQuestions
        originalQuestionRepository.hardDelete(versionId);
        //删除该版本下不活跃的StandardQuestions
        standardQuestionRepository.hardDelete(versionId);

        return versionRepository.findById(versionId).get();
    }

    @Override
    @Transactional
    public List<Version> getPublished() {
        return versionRepository.findByPublished(true);
    }
    public List<Version> getUnpublished() {
        return versionRepository.findByPublished(false);
    }

    @Override
    public Version getVersion(String versionId) throws IllegalArgumentException {
        Optional<Version> versionOpt = versionRepository.findById(versionId);
        if (versionOpt.isEmpty()) {
            throw new IllegalArgumentException("Version " + versionId + " not found");
        }
        return versionOpt.get();
    }

    @Override
    public List<Version> getAllVersions() {
        return versionRepository.findAllVersions();
    }
}
